/**
 * 用户相关服务
 */

const util = require('../utils/util.js');
const api = require('../config/api.js');


/**
 * 调用微信登录
 */
function loginByWeixin(userInfo) {

  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then((res) => {
      code = res.code;
      return userInfo;
    }).then((userInfo) => {
      //登录远程服务器
      util.request(api.AuthLoginByWeixin, { code: code, userInfo: JSON.stringify(userInfo) }, 'POST').then(res => {
        
        if (res.status === 1) {
          wx.showToast({
            title: '登录成功',
          });
          //存储用户信息
          
          wx.setStorageSync('userInfo', res.userInfo);
          wx.setStorageSync('token', res.token);
          wx.setStorageSync('user_id', res.user_id);

          resolve(res);
        } else if (res.status === 2){
          wx.setStorageSync('openid', res.result);
          wx.setStorageSync('avatarUrl', res.avatarUrl);
          wx.setStorageSync('nickName', res.nickName);
          wx.navigateTo({
            url: '/pages/auth/mobile/mobile',
          })
        }else {
          util.showErrorToast(res.errmsg)
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

function loginByWeixinxxc(userInfo) {

  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then((res) => {
      code = res.code;
      return userInfo;
    }).then((userInfo) => {
      //登录远程服务器
      util.request(api.getInviterInfo, { code: code, userInfo: JSON.stringify(userInfo) }, 'POST').then(res => {

        if (res.status === 1) {
          wx.showToast({
            title: '登录成功',
          });
          //存储用户信息
          console.log('小程序登录成功返回的数据' + res);
          wx.setStorageSync('userInfo', res.userInfo);
          wx.setStorageSync('token', res.token);
          wx.setStorageSync('user_id', res.user_id);
          wx.setStorageSync('inviter_info', res.inviter_info);

          resolve(res);
        } else {
          util.showErrorToast(res.errmsg)
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {

      util.checkSession().then(() => {
        resolve(true);
      }).catch(() => {
        reject(false);
      });

    } else {
      reject(false);
    }
  });
}


module.exports = {
  loginByWeixin,
  loginByWeixinxxc,
  checkLogin,
};











